<template>
	<div
		v-if="isExternal"
		:style="styleExternalIcon"
		class="svg-external-icon svg-icon"
		v-bind="$attrs"
	/>
	<svg
		v-else
		:class="svgClass"
		aria-hidden="true"
		v-bind="$attrs"
	>
		<use :xlink:href="iconName"/>
	</svg>
</template>

<script setup lang="ts">
import { computed } from 'vue';

// 定义组件属性
const props = defineProps({
	iconClass: {
		type: String,
		required: true
	},
	className: {
		type: String,
		default: ''
	}
});

// 计算属性
const isExternal = computed(() => {
	return /^(https?:|mailto:|tel:)/.test(props.iconClass);
});

const iconName = computed(() => {
	return `#icon-${props.iconClass}`;
});

const svgClass = computed(() => {
	if (props.className) {
		return props.className + ' svg-icon';
	} else {
		return 'svg-icon';
	}
});

const styleExternalIcon = computed(() => {
	return {
		mask: `url(${props.iconClass}) no-repeat 50% 50%`,
		'-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`
	};
});

// 定义组件名称
defineExpose({
	name: 'SvgIcon'
});
</script>

<style scoped>
.svg-icon {
	vertical-align: -0.15em;
	fill: currentColor;
	overflow: hidden;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
	height: 100%;
	width: 100%;
}

.svg-external-icon {
	background-color: currentColor;
	mask-size: cover !important;
	display: inline-block;
}
</style>
